package com.sync.hkmjsyncdata.task;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkRegion;
import com.sync.hkmjsyncdata.service.IHkRegionService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SyncMjRegion {

    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;

    @Resource
    IHkRegionService hkRegionService;






    //{"code":"0","msg":"success","data":{"total":2,"pageNo":1,"pageSize":100,"list":[{"indexCode":"root000000","name":"根节点","parentIndexCode":"-1","treeCode":"0"},{"indexCode":"1fda1876446d474f9ae39b4b8aa156cc","name":"超脑","parentIndexCode":"root000000","treeCode":"0"}]}}

















    /**
     * 同步海康区域
     */
    @XxlJob("syncMjRegion")
    public void syncMjRegionData(){
        XxlJobHelper.log("开始同步海康区域信息");
        LambdaQueryWrapper<HkRegion> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(HkRegion::getOpTyp,4)
                        .last(" limit 1");
        List<HkRegion> allResult=hkRegionService.list();
        if(ObjectUtils.isNotEmpty(allResult)){
            XxlJobHelper.log("数据库已有海康区域信息：{}条", allResult.size());
//            List<HkRegion> result=hkRegionService.list(queryWrapper);
//            if(ObjectUtils.isEmpty(result)){
//                XxlJobHelper.log("数据库已有海康区域信息未推送工业互联网,停止拉取");
//                return;
//            }
        }
        List<HkRegion> newRegions=new ArrayList<>();
        syncMjRegionDataByHk(1,newRegions);
        buidRegionInfo(allResult,newRegions);
    }


    private void syncMjRegionDataByHk(int pageNo, List<HkRegion> newRegions) {

        JSONObject regionParams = new JSONObject();
        regionParams.put(PAGE_NO_KEY, pageNo);
        regionParams.put(PAGE_SIZE_KEY, 1000);
        regionParams.put("resourceType","door");
        XxlJobHelper.log("同步海康区域信息查询条件：{}", regionParams.toJSONString());
        String resultInfo = centerUtilsService.doPost("/api/irds/v1/region/nodesByParams", regionParams.toJSONString());
        XxlJobHelper.log("同步海康区域信息返回：{}", resultInfo);
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject regionResult= JSON.parseObject(resultInfo);
            JSONObject regionData = regionResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(regionData) && ObjectUtils.isNotEmpty(regionData.getJSONArray("list"))) {
                JSONArray list = regionData.getJSONArray("list");
                for (int i = 0; i < list.size(); i++) {
                    JSONObject regionInfo = list.getJSONObject(i);
                    newRegions.add(new HkRegion().setAreaId(regionInfo.getString("indexCode"))
                            .setAreaName(regionInfo.getString("name"))
                            .setAreaNot(regionInfo.getString("name"))
                            .setUpAreaId(regionInfo.getString("parentIndexCode"))
                            .setOpTyp(1));
                }
                if(ObjectUtils.isNotEmpty(list)){
                    syncMjRegionDataByHk(pageNo+1,newRegions);
                }
            } else {
                XxlJobHelper.log("同步海康区域信息失败");
            }
        }


    }

    protected void buidRegionInfo(List<HkRegion> allResult, List<HkRegion>  hkRegionList) {
        Map<String, HkRegion> oldRegionMap = allResult.stream().collect(Collectors.toMap(HkRegion::getAreaId, regin -> regin, (a, b) -> b));
        if(ObjectUtils.isEmpty(oldRegionMap)){
            hkRegionService.saveBatch(hkRegionList);
        }else {
            List<HkRegion> addHkRegionList=new ArrayList<>();
            List<HkRegion> updateHkRegionList=new ArrayList<>();
            List<String> ids=new ArrayList<>();
            hkRegionList.forEach(region->{
                ids.add(region.getAreaId());
                HkRegion oldRegion=oldRegionMap.get(region.getAreaId());
                if(ObjectUtils.isEmpty(oldRegion)){
                    addHkRegionList.add(region);
                }else {
                    updateHkRegionList.add(region.setOpTyp(oldRegion.getOpTyp()==4?2:oldRegion.getOpTyp()));
                }
            });
            List<HkRegion> deleteRegionList=allResult.stream().filter(region->(!ids.contains(region.getAreaId()))&&region.getOpTyp()==4).toList();
            deleteRegionList.forEach(nreg->nreg.setOpTyp(3));
            XxlJobHelper.log("新增海康区域信息：{}条",addHkRegionList.size());
            hkRegionService.saveBatch(addHkRegionList);
            XxlJobHelper.log("修改海康区域信息：{}条",updateHkRegionList.size());
            hkRegionService.updateBatchById(updateHkRegionList);
            XxlJobHelper.log("删除海康区域信息：{}条",deleteRegionList.size());
            hkRegionService.updateBatchById(deleteRegionList);
        }
    }

}
